package com.zzzy.cont.controller;

import com.zhuozhengsoft.pageoffice.FileSaver;
import com.zhuozhengsoft.pageoffice.OpenModeType;
import com.zhuozhengsoft.pageoffice.PageOfficeCtrl;
import com.zhuozhengsoft.pageoffice.word.DataRegionReader;
import com.zhuozhengsoft.pageoffice.word.WordDocumentReader;
import com.zhuozhengsoft.pageoffice.word.WordDocumentWriter;
import com.zzzy.common.enums.YesOrNoEnum;
import com.zzzy.common.util.FileUtil;
import com.zzzy.common.vo.AjaxResult;
import com.zzzy.common.vo.PageResult;
import com.zzzy.cont.dao.entity.ConFileTemplate;
import com.zzzy.cont.service.ConFileTemplateService;
import com.zzzy.cont.vo.template.*;
import com.zzzy.framework.common.enums.common.TemplateStatusEnum;
import com.zzzy.framework.common.util.SecurityUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;

/**
 * 合同模板 前端控制器
 *
 * @author fc
 * @since 2024-05-22
 */
@Tag(name = "合同模板", description = "con000")
@Validated
@RestController
@RequestMapping("/con/fileTemplate")
public class ConFileTemplateController {

    @Resource
    private ConFileTemplateService conFileTemplateService;

    @GetMapping(value = "/page")
    @Operation(summary = "分页列表")
    @PreAuthorize("@pvs.hasPermission('con:fileTemplate:page')")
    public AjaxResult<PageResult<ConFileTemplatePageRes>> page(@Valid @ParameterObject ConFileTemplatePageReq queryReq) {
        PageResult<ConFileTemplatePageRes> conFileTemplatePage = conFileTemplateService.getConFileTemplateResPage(queryReq);
        return AjaxResult.success(conFileTemplatePage);
    }

    @PostMapping("/add")
    @Operation(summary = "新增模板,返回模板ID")
    @PreAuthorize("@pvs.hasPermission('con:fileTemplate:add')")
    public AjaxResult<Long> add(@Valid @RequestBody ConFileTemplateAddReq addReq) {
        return AjaxResult.success(conFileTemplateService.addConFileTemplate(addReq));
    }

    @GetMapping("/getBasicInfo/{id}")
    @Operation(summary = "获取模板基本信息")
    @Parameter(name = "id", description = "合同模板ID", required = true)
    @PreAuthorize("@pvs.hasPermission('con:fileTemplate:page')")
    public AjaxResult<ConFileTemplate> getBasicInfo(@NotNull(message = "合同模板ID不能为空") @PathVariable("id") Long id) {
        ConFileTemplate conFileTemplate = conFileTemplateService.getConFileTemplateSimpleById(id);
        return AjaxResult.success(conFileTemplate);
    }

    @PutMapping("/updateBasicInfo")
    @Operation(summary = "修改模板基本信息")
    @PreAuthorize("@pvs.hasPermission('con:fileTemplate:update')")
    public AjaxResult updateBasicInfo(@Valid @RequestBody ConFileTemplateSimpleUpdateReq updateReq) {
        conFileTemplateService.updateBasicInfoById(updateReq);
        return AjaxResult.success();
    }

    @DeleteMapping("/delete/{id}")
    @Operation(summary = "删除模板")
    @Parameter(name = "id", description = "合同模板ID", required = true)
    @PreAuthorize("@pvs.hasPermission('con:fileTemplate:delete')")
    public AjaxResult delete(@NotNull(message = "合同模板ID不能为空") @PathVariable("id") Long id) {
        conFileTemplateService.deleteById(id);
        return AjaxResult.success();
    }

    @GetMapping(value = "/getOpenTemplateWordRes/{id}")
    @Operation(summary = "打开模板文件")
    @Parameter(name = "id", description = "合同模板ID", required = true)
    @PreAuthorize("@pvs.hasPermission('con:fileTemplate:page')")
    public AjaxResult<OpenConTemplateWordRes> getOpenTemplateWordRes(@NotNull(message = "模板ID不能为空") @PathVariable("id") Long id, HttpServletRequest request) {
        ConFileTemplate conFileTemplate = conFileTemplateService.getConFileTemplateSimpleById(id);
        //work打开方式
        OpenModeType openModeType;
        //只有新建状态且为创建人才能修改模板,其他人只能查看
        if (TemplateStatusEnum.CREATE.getValue().equals(conFileTemplate.getStatus()) && SecurityUtils.getLoginUser().getId().equals(conFileTemplate.getUserId())){
            openModeType = OpenModeType.docNormalEdit;
        } else {
            openModeType = OpenModeType.docReadOnly;
        }
        PageOfficeCtrl poCtrl = new PageOfficeCtrl(request);
        poCtrl.setWriter(new WordDocumentWriter());
        //打开Word文档地址
        poCtrl.webOpen("/con/fileTemplate/getTemplateWordStream/" + id, openModeType, SecurityUtils.getLoginUser().getNickName());
        List<String> dataTagList = new ArrayList<>();
        dataTagList.add("【交易公司名称】");
        dataTagList.add("【合同编号】");
        dataTagList.add("【订单编号】");
        dataTagList.add("【合同金额】");
        dataTagList.add("【合同金额-中文大写】");
        OpenConTemplateWordRes wordRes = new OpenConTemplateWordRes();
        wordRes.setHtml(poCtrl.getHtml());
        wordRes.setFixedFormat(YesOrNoEnum.YES.getValue().equals(conFileTemplate.getIsFixedFormat()));
        wordRes.setDataRegions(conFileTemplate.getDataRegions());
        wordRes.setDataTags(dataTagList);
        ConFileTemplatePageRes.Button button = conFileTemplateService.getButton(id);
        wordRes.setSave(button.isUpdate());
        return AjaxResult.success(wordRes);
    }

    @GetMapping(value = "/getTemplateWordStream/{id}")
    @Operation(summary = "获取模板文件流")
    @Parameter(name = "id", description = "合同模板ID", required = true)
    @PreAuthorize("@pvs.hasPermission('con:fileTemplate:page')")
    public void getTemplateWordStream(@NotNull(message = "合同模板ID不能为空") @PathVariable("id") Long id, HttpServletResponse response) {
        ConFileTemplate conFileTemplate = conFileTemplateService.getConFileTemplateByIdForQuery(id);
        FileUtil.outputFileStream(response, conFileTemplate.getFileBlob(), conFileTemplate.getName() + "." + conFileTemplate.getFileExtName());
    }

    @PostMapping(value = "/updateTemplateWord/{id}")
    @Operation(summary = "修改模板文件")
    @Parameter(name = "id", description = "合同模板ID", required = true)
    @PreAuthorize("@pvs.hasPermission('con:fileTemplate:update')")
    public void updateTemplateWord(@NotNull(message = "合同模板ID不能为空") @PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response) {
        FileSaver fs = new FileSaver(request, response);
        byte[] byteArray = FileUtil.toByteArray(fs.getFileStream());
        conFileTemplateService.updateTemplateWord(id, byteArray, fs.getFileExtName());
        fs.setCustomSaveResult("ok");
        fs.close();
    }

    @PostMapping(value = "/updateTemplateDataRegion/{id}")
    @Operation(summary = "保存模板数据区域")
    @Parameter(name = "id", description = "公文模板ID", required = true)
    @PreAuthorize("@pvs.hasPermission('doc:fileTemplate:update')")
    public void updateTemplateDataRegion(@NotNull(message = "公文模板ID不能为空") @PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response) {
        WordDocumentReader wordDocumentReader = new WordDocumentReader(request, response);
        List<DataRegionReader> dataRegions = wordDocumentReader.getDataRegions();
        conFileTemplateService.updateTemplateDataRegion(id, dataRegions);
        wordDocumentReader.setCustomSaveResult("ok");
        wordDocumentReader.close();
    }

    @PutMapping("/clone/{id}")
    @Operation(summary = "克隆模板,返回模板ID")
    @Parameter(name = "id", description = "合同模板ID", required = true)
    @PreAuthorize("@pvs.hasPermission('con:fileTemplate:add')")
    public AjaxResult<Long> clone(@NotNull(message = "合同模板ID不能为空") @PathVariable("id") Long id) {
        return AjaxResult.success(conFileTemplateService.cloneById(id));
    }

    @PutMapping("/enable/{id}")
    @Operation(summary = "启用模板")
    @Parameter(name = "id", description = "合同模板ID", required = true)
    @PreAuthorize("@pvs.hasPermission('con:fileTemplate:add')")
    public AjaxResult enable(@NotNull(message = "合同模板ID不能为空") @PathVariable("id") Long id) {
        conFileTemplateService.enable(id);
        return AjaxResult.success();
    }

    @PutMapping("/disable/{id}")
    @Operation(summary = "停用模板")
    @Parameter(name = "id", description = "合同模板ID", required = true)
    @PreAuthorize("@pvs.hasPermission('con:fileTemplate:add')")
    public AjaxResult disable(@NotNull(message = "合同模板ID不能为空") @PathVariable("id") Long id) {
        conFileTemplateService.disable(id);
        return AjaxResult.success();
    }
}
